from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from . import models,serializer
# Create your views here.


'''
1 前端传什么格式数据
-{course:[1,2,3],total_amount:100,subject:xx商品,pay_type:1,}
2 后端接到数据要校验
-course:[1,2,3]===》course:[obj1，obj2，obj3]
-在序列化类中：course=serializers.PrimaryKeyRelatedField(queryset=Course.objects.all(), write_only=True, many=True)
3 在序列化类的validate中处理一堆逻辑
    1）订单总价校验：
        一个个课程价格取出来累加看是否等于传入的总价格
    2）生成订单号
        -通过uuid生成
    3）支付用户：request.user
        -通过视图和序列化类之间的桥梁context对象传递
        -重新视图类中的create方法，把request对象放入context
        -self.context.get('request').user
    4）支付链接生成
        -导入封装的支付宝支付，生成
        	order_string = alipay.api_alipay_trade_page_pay    (
            out_trade_no=out_trade_no,
            total_amount=total_amout,
            subject=subject,
            return_url=settings.RETURN_URL,  # get回调，前台地址
            notify_url=settings.NOTIFY_URL   # post回调，后台地址
        )
    5）入库(两个表)的信息准备
        -把user放入attrs中
        -把订单号，放入attrs中
        	attrs['user']=user
        	attrs['out_trade_no']=out_trade_no
        	self.context['pay_url']=pay_url
4 重写序列化类的create方法
-把course_list弹出来
-order=models.Order.objects.create(**validated_data)
'''
class PayView(GenericViewSet,CreateModelMixin):
    authentication_classes = [JSONWebTokenAuthentication,]
    permission_classes = [IsAuthenticated]
    queryset = models.Order.objects.all()
    serializer_class = serializer.OrderSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.context.get('pay_url'))

# 支付宝回调接口
class SuccessView(APIView):
    def get(self, request, *args, **kwargs):
        out_trade_no = request.query_params.get('out_trade_no')
        order = models.Order.objects.filter(out_trade_no=out_trade_no).first()
        if order.order_status == 1:
            return Response(True)
        else:
            return Response(False)

    def post(self, request, *args, **kwargs):
        '''
        支付宝回调接口
        '''
        from luffyapi.libs.al_pay import alipay
        from luffyapi.utils.logger import log
        data = request.data
        out_trade_no = data.get('out_trade_no', None)
        gmt_payment = data.get('gmt_payment', None)
        signature = data.pop("sign")
        # 验证签名
        success = alipay.verify(data, signature)
        if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            models.Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1, pay_time=gmt_payment)
            log.info('%s订单支付成功' % out_trade_no)
            return Response('success')
        else:
            log.info('%s订单有问题' % out_trade_no)
            return Response('error')